package com.jgp.sys.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Objects;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2018/5/29
 */
public class UrlUtil {
    
    /**
     * 通过controller上配置的url转换成模板页面访问路径
     *
     * @param clazz
     * @return
     */
    public static String getPageTemplateDirFromController(Class clazz) {
        String[] paths = null;
        RequestMapping annotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
        GetMapping annotation2 = (GetMapping) clazz.getAnnotation(GetMapping.class);
        if (Objects.nonNull(annotation)) {
            paths = annotation.value();
        } else if (Objects.nonNull(annotation2)) {
            paths = annotation2.value();
        }
        String targetDir = Objects.nonNull(paths) && paths.length > 0 ? paths[0] : "";
        if (StringUtils.isNotBlank(targetDir)) {
            if (targetDir.endsWith("Controller")) {
                targetDir = targetDir.replaceAll("(/\\w+)Controller", "");
            } else if (targetDir.endsWith("-ctl")) {
                targetDir = targetDir.replaceAll("(/(\\w|-)+)-ctl", "");
            }
            if (targetDir.charAt(0) == '/') targetDir = targetDir.substring(1);
            if ("".equals(targetDir)) {
                return "/";
            } else if (targetDir.charAt(targetDir.length() - 1) != '/') targetDir = targetDir + "/";
        }
        return targetDir;
    }
    
}


